package com.yunupmall.controller.ford;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunupmall.api.fordVO.OrderVo;
import com.yunupmall.api.fordentity.Order;
import com.yunupmall.api.po.OrderByidPo;
import com.yunupmall.api.po.OrderPagePO;
import com.yunupmall.service.ford.service.OrderService;
import com.yunupmall.uits.ReadUtils;
import com.yunupmall.uits.Result;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

@Controller
@AllArgsConstructor
@RequestMapping("/order")
public class OrderController {
   private final OrderService orderService;

    private final Result result;
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg//3meVzoOeC5E/M1TTwtyC+IV62DprhqAy6UC9VKlqNJlcdnfN2Y01QBanDaCFmN8IFA2cy5mff/X86tH4GQ58ful/e1MhBM2jkSdjdgQ5060ksI3A8/r3Ic/cl77Dow7+J51uSXMI9mr1xbZVDyUMsHtdbAH9Eue31osPzrOaPxljg8jk02SfA6xiSSpyWytvgXZLLNnp1brPC0/tAwxAz9nkBGyWfhu/vEqkmNAIf/9mVfJGnvmJnXxSTI4aaJGkRslJD7g4RfRXtXACkuRUWptIFFtHo7hTAIZuohPyynK7oMuv3hK0pt18Y0AnI3xEv94qwilrZVd+9lqfevwIDAQAB";
    //签名方式
    private final String SIGN_TYPE = "RSA2";



   @PostMapping("/save")
   @ResponseBody
    public Result save(@RequestBody OrderVo orderVo){
       try {
            return orderService.saveData(orderVo);
       }catch (Exception e) {
            return result.error(e.getMessage());
       }
   }
   @PostMapping("/returnOrderData")
    public ModelAndView returnOrderData(HttpServletRequest request){
       ModelAndView modelAndView = new ModelAndView();
       try {
           String s = orderService.returnData(request);
           modelAndView.addObject("s");
           modelAndView.setViewName("index");
           return modelAndView;
       }catch (Exception e) {
           modelAndView.setViewName("index");
           modelAndView.addObject(e.getMessage());
           return modelAndView;
       }
   }
    /**
     * 异步轮询
     */
    @GetMapping("/polling")
    @ResponseBody
    public Result polling(@RequestParam  String uuid){
        try {
           return orderService.polling(uuid);
        }catch (Exception e) {
           return result.error(e.getMessage());
        }
    }

    /**
     * 页面获取订单信息
     */
   @PostMapping("/page")
   @ResponseBody
   public Result<Page<OrderPagePO>> page(@RequestBody OrderVo orderVo){
       try {
           return result.ok(orderService.pageData(orderVo));
       }catch (Exception e) {
           return result.error(e.getMessage());
       }
   }
    /**
     * 删除
     */
    @GetMapping("/del")
    @ResponseBody
    public Result<String> del(@RequestParam Integer id){
        try {
            return result.ok(orderService.del(id));
        }catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
    /**
     * 根据订单ID修改订单状态
     */
    @GetMapping("/byidUpdate")
    @ResponseBody
    public Result<String> byidUpdate(@RequestParam Integer id,@RequestParam Integer statics){
        try {
            return result.ok(orderService.byidUpdate(id,statics));
        }catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
    /**
     * 创建订单未付款
     */
    @GetMapping("/pay")
    @ResponseBody
    public Result<String> pay(@RequestParam Integer id){
        try {
            return result.ok(orderService.pay(id));
        }catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
    /**
     * 订单详情
     */
    @GetMapping("/byid")
    @ResponseBody
    public Result<OrderByidPo> byid(@RequestParam Integer id){
        try {
            return result.ok(orderService.byid(id));
        }catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
    /**
     * 修改订单
     */
    @PostMapping("/update")
    @ResponseBody
    public Result<String> update(@RequestBody OrderVo orderVo){
        try {
            return result.ok(orderService.updateDate(orderVo));
        }catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
    /**
     * 物流信息查询
     */
    @GetMapping("/getlogistics")
    @ResponseBody
    public Result<String> getlogistics(@RequestParam  Integer id){
        Order byId = orderService.getById(id);
        String host = "https://wuliu.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/kdi";  // 【2】后缀
        String appcode = "fc21b82ed4244f1a9ea58c7d1f913902"; // 【3】开通服务后 买家中心-查看AppCode
        String no = byId.getNumber();// 【4】请求参数，详见文档描述
        String urlSend = host + path + "?no=" + no;  // 【5】拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon .setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = ReadUtils.read(httpURLCon.getInputStream());
                JSONObject jsonObject = JSON.parseObject(json);
                System.out.printf(jsonObject.toString());
                return result.ok(jsonObject);
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    return result.error("AppCode错误");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    return result.error("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    return result.error("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    return result.error("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    return result.error("套餐包次数用完");
                } else if (httpCode == 403 && error.equals("Api Market Subscription quota exhausted")) {
                    return result.error("套餐包次数用完，请续购套餐");
                } else {
                    return result.error("参数名错误 或 其他错误");
                }
            }

        } catch (MalformedURLException e) {
            return result.error("URL格式错误");
        } catch (UnknownHostException e) {
            return result.error("URL地址错误");
        } catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
}
